package threadcoreknowledge.sixstates.scy;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 注意 notify方法,必须在持有锁对象的时候调用,当在synchronized代码块之外调用,会报错
 * 持有锁对象的线程,在调用notify方法后,并不会立即释放掉锁,而是走出代码块才会释放锁对象
 */
public class WaitingState {

    public static void main(String[] args) throws Exception {
      final  Object lock = new Object();

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("thread1执行了");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        System.out.println("-----thread1进入catch了-----");
                        throw new RuntimeException(e);
                    }
                    System.out.println("------thread1正常结束了-------");
                }

            }
        }, "线程1");


        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("thread2执行了");
                    Long _long = 0L;
                    long start = System.currentTimeMillis();
                    for (long i = 0; i <=359_999_999L; i++) {
                        Random random = new Random();
                        int seed = random.nextInt(100);
                        Random random1 = new Random(seed);
                        int i1 = random1.nextInt(100);
                        _long = i1 + _long;
                    }
                    long end = System.currentTimeMillis();

                    System.out.println("程序耗时:" + (end - start) + "毫秒-----运行结果是:"+_long);
                    lock.notify(); // 注意 notify方法,必须在持有锁对象的时候调用,当在synchronized代码块之外调用,会报错
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("thread2中lock执行notify方法结束了");
                }
                    System.out.println("thread2跳出循环");

            }
        }, "线程2");


        thread1.start();
        thread2.start();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

        while (true) {
            System.out.println("thread1线程状态:" + thread1.getState() + "------" + simpleDateFormat.format(new Date()));
            System.out.println("thread2线程状态:" + thread2.getState() + "------" + simpleDateFormat.format(new Date()));
            Thread.sleep(1000*2);
            if (thread1.getState().equals(Thread.State.TERMINATED)) {
                if (thread2.getState().equals(Thread.State.TERMINATED)) {
                    break;
                }
            }
            System.out.println("---------------------------------");

        }


    }
}
